package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * http协议工具类
 * @author wangshaoming
 *
 */
public class HttpUtils {
	/**
	 * get请求
	 * @param url
	 */
	public static String doGet(String url){
		InputStream is=null;
		StringBuffer buffer=new StringBuffer(2048);
		BufferedReader br=null;
		try {
			URL urlGet=new URL(url);
			HttpURLConnection http=(HttpURLConnection)urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setReadTimeout(10000);
			http.setConnectTimeout(10000);
			http.setRequestProperty("Content-type", "text/html; charset=utf-8");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			is=http.getInputStream();
			if(!http.getContentType().contains("text/html")){
				return "";
			}
			br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line="";
			while((line=br.readLine())!=null){
				buffer.append(line);
			}
			String message=buffer.toString();
			return message;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
	
	
	/**
	 * 发送post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url,String json){
		try{
			URL action = new URL(url);
			HttpURLConnection http=(HttpURLConnection)action.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			//设置超时时间
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");
			http.connect();
			OutputStream os=http.getOutputStream();
			os.write(json.getBytes("UTF-8"));
			os.flush();
			os.close();
			InputStream is=http.getInputStream();
			int size=is.available();
			byte[] jsonBytes=new byte[size];
			is.read(jsonBytes);
			String message=new String(jsonBytes,"UTF-8");
			return message;
		}catch(MalformedURLException e){
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}
